#pragma once
#ifndef texture_loader_hpp
#define texture_loader_hpp

#include <SDL/SDL.h>
#include <SDL/SDL_opengl.h>
#include <SDL/SDL_image.h>
#include <string>

#define BMP "bmp"
#define CUR "cur"
#define GIF "gif"
#define ICO "ico"
#define JPG "jpg"
#define LBM "lbm"
#define PCX "pcx"
#define PNG "png"
#define PNM "pnm"
#define TGA "tga"
#define TIF "tif"
#define XCF "xcf"
#define XPM "xpm"
#define XV "xv"
#define N_IMAGE_TYPE 14

static const char* IMAGE_FILE_TYPES[N_IMAGE_TYPE] ={(char*)BMP,(char*)CUR,(char*)GIF,(char*)ICO,(char*)JPG,(char*)LBM,(char*)PCX,(char*)PNG,(char*)PNM,(char*)TGA,(char*)TIF,(char*)XCF,(char*)XPM,(char*)XV};

int load_texture(char* texture_file_name, GLuint* texture){
 //GLuint texture= 0;
 SDL_Surface *surface= NULL;
 GLenum texture_format;
 GLint  n_colors;

 //printf("Loading texture: %s\n",texture_file_name);

 int i= 0;
 std::string t_file;
 while((i< N_IMAGE_TYPE) && (!surface)){
  if(!(surface= IMG_Load(texture_file_name))){
   t_file= texture_file_name;
   t_file+= ".";
   t_file+= IMAGE_FILE_TYPES[i];
   surface= IMG_Load(t_file.c_str());
   /*if(!(surface= IMG_Load(t_file.c_str()))){
    t_file= texture_file_name;
    t_file+= ".";
    t_file+= IMAGE_FILE_TYPES[i];
   }*/
  }
  i++;
 }
 if((i== N_IMAGE_TYPE) || (!surface)){
  fprintf(stderr,"SDL could not load %s: %s\n",texture_file_name,SDL_GetError());
  return 0;
 }
 printf("Loaded texture: %s.%s\n",texture_file_name,IMAGE_FILE_TYPES[--i]);

 //a magassag es szelesseg 2 tobbszorose kell legyen
	if((surface->w & (surface->w-1))!= 0){
		fprintf(stderr,"Image width not power of 2: %s\n,",texture_file_name);
  return 0;
	}
 if((surface->h & (surface->h-1))!= 0){
		fprintf(stderr,"Image heigth not power of 2: %s\n",texture_file_name);
  return 0;
	}

 //a szincsatornak szama
 n_colors= surface->format->BytesPerPixel;
 if(n_colors== 4){//van alfacsatorna
  if(surface->format->Rmask== 0x000000ff){
   texture_format= GL_RGBA;
  }else{
   texture_format= GL_BGRA;
  }
 }else{
  if(n_colors == 3){//nincs alfa csatona
   if(surface->format->Rmask== 0x000000ff){
    texture_format= GL_RGB;
   }else{
    texture_format= GL_BGR;
   }
  }else{
   printf("WARNING: not truecolor\n");
   return 0;
  }
 }

 //printf("%d %d %d\n",n_colors,surface->w,surface->h);

 glGenTextures(1,texture);
	glBindTexture(GL_TEXTURE_2D,*texture);
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_LINEAR);
 glTexParameteri(GL_TEXTURE_2D,GL_GENERATE_MIPMAP,GL_TRUE);
 glTexImage2D(GL_TEXTURE_2D,0,n_colors,surface->w,surface->h,0,texture_format,GL_UNSIGNED_BYTE,surface->pixels);
 /*glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
 glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);*/

 //printf("%d\n",*texture);

 if(surface){
	 SDL_FreeSurface(surface);
 }
 return 0;
}

#endif
